package com.shuqi.model.bean;

import java.io.Serializable;
import java.util.List;

import android.text.TextUtils;

import com.shuqi.application.ShuqiApplication;
import com.shuqi.bookcontent.BookContentRender;
import com.shuqi.common.Constant;
import com.shuqi.common.utils.BookContentUtils;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.model.BookCataLog;
import com.shuqi.database.model.BookInfo;
import com.shuqi.model.BookContentModel;
import com.shuqi.model.parse.BookContentParserBase;

/**
 * 阅读页数据
 * 
 * @remark 章节ID，索引，文件名字，路径等信息
 * @author Jianda.Yang
 * @date 2013-12-10 上午11:52:20
 * @version 1.0
 */
public class BookContentInfo implements Serializable {
    private static final long serialVersionUID = 1L;
    private final int PRE_CHAPTER = 0;
    private final int CUR_CHAPTER = 1;
    private final int NEXT_CHAPTER = 2;

    private String uid;
    /** 书籍ID */
    private String bookId;
    /** 来源ID */
    private String sourceId;
    /** 书籍名字 */
    private String bookname;
    /** 书签索引 */
    private long markIndex;
    /** 文件路径 */
    private String fliePath;
    /** 本地书籍：文件大小 */
    private int totalLength;
    /** 书籍类型：Constant.BOOKTYPE_ **/
    private int type;
    /** 编码 */
    private String encoding;
    /** 小封面图URL */
    private String imageUrl;
    /** 书籍阅读页状态为是否开放 */
    private boolean isOpen;
    /** 书籍是否为隐藏书籍 */
    private boolean isHide;
    /** 作者 */
    private String author;
    /** 是否需要购买 */
    private boolean isNeedBuy;
    /** 老书签与收费书签置换 */
    private boolean isOld;
    /** 错误信息 */
    private String errorMessage;

    private BookChapterInfo mPrevChapter;
    private BookChapterInfo mCurChapter;
    private BookChapterInfo mNextChapter;
    private int mCurChapterLineIndex;
    private int mCurSreenLineCount;
    private BookInfo mBookInfo;

    public BookContentInfo() {
        mPrevChapter = new BookChapterInfo(this);
        mCurChapter = new BookChapterInfo(this);
        mNextChapter = new BookChapterInfo(this);
    }

    public void setBookInfo(BookInfo bookInfo) {
        mBookInfo = bookInfo;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    @Override
    public String toString() {
        return "PayChapterInfo [PRE_CHAPTER="
                + PRE_CHAPTER
                + ", CUR_CHAPTER="
                + CUR_CHAPTER
                + ", NEXT_CHAPTER="
                + NEXT_CHAPTER
                + ", bookId="
                + bookId
                + ", uid="
                + uid
                + ", encoding="
                + encoding
                + ", discountPrice="
                + ", wordCounts="
                + ", curChapterType="
                + mCurChapter.getChapterType()
                + ", curChapterBytes.length="
                + (mCurChapter.getChapterBytes() == null ? "null"
                        : mCurChapter.getChapterBytes().length) + "]";
    }

    public BookChapterInfo getCurChapter() {
        return mCurChapter;
    }

    public BookChapterInfo getPrevChapter() {
        return mPrevChapter;
    }

    public BookChapterInfo getNextChapter() {
        return mNextChapter;
    }

    public void setCurChapterLineIndex(int index) {
        mCurChapterLineIndex = index;
    }

    public int getCurChapterLineIndex() {
        return mCurChapterLineIndex;
    }

    public void setCurSreenLineCount(int count) {
        mCurSreenLineCount = count;
    }

    public int getCurSreenLineCount() {
        return mCurSreenLineCount;
    }

    public boolean isOld() {
        return isOld;
    }

    public void setOld(boolean isOld) {
        this.isOld = isOld;
    }

    public String getSourceId() {
        return sourceId;
    }

    public void setSourceId(String sourceId) {
        this.sourceId = sourceId;
    }

    public boolean isNeedBuy() {
        return isNeedBuy;
    }

    public void setNeedBuy(boolean isNeedBuy) {
        this.isNeedBuy = isNeedBuy;
    }

    public String getChapterpath() {
        return mCurChapter.getChapterpath();
    }

    public void setChapterpath(String chapterpath) {
        this.mCurChapter.setChapterpath(chapterpath);
    }

    public boolean isOpen() {
        return isOpen;
    }

    public void setOpen(boolean isOpen) {
        this.isOpen = isOpen;
    }

    public boolean isHide() {
        return isHide;
    }

    public void setHide(boolean isHide) {
        this.isHide = isHide;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    /** 书籍类型：Constant.BOOKTYPE_ **/
    public int getType() {
        return type;
    }

    /** 书籍类型：Constant.BOOKTYPE_ **/
    public void setType(int type) {
        this.type = type;
    }

    public String getEncoding() {
        return encoding;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public int getStartIndex() {
        return mCurChapter.getStartIndex();
    }

    public void setStartIndex(int startIndex) {
        this.mCurChapter.setStartIndex(startIndex);
    }

    public int getEndIndex() {
        return mCurChapter.getEndIndex();
    }

    public void setEndIndex(int endIndex) {
        this.mCurChapter.setEndIndex(endIndex);
    }

    public long getMarkIndex() {
        return markIndex;
    }

    public void setMarkIndex(long markIndex) {
        this.markIndex = markIndex;
    }

    public void setCurChapterVid(String vid) {
        this.mCurChapter.setChapterVid(vid);
    }

    public String getCurChapterVid() {
        return mCurChapter.getChapterVid();
    }

    public String getBookId() {
        return bookId;
    }

    public void setBookId(String bookId) {
        this.bookId = bookId;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    /**
     * 1则成功获取信息,其他失败
     * 
     * @param curChapterType
     */
    public void setCurChapterType(String curChapterType) {
        this.mCurChapter.setChapterType(curChapterType);
    }

    /**
     * 获取当前章节内容的字节数组
     * 
     * @return curChapterInfo
     */
    public byte[] getCurChapterBytes() {
        return mCurChapter.getChapterBytes();
    }

    /**
     * 设置当前章节内容的字节数组
     * 
     * @param
     */
    public void setCurChapterBytes(byte[] curChapterBytes) {
        this.mCurChapter.setChapterBytes(curChapterBytes);
    }

    /** 获取章节内容返回的消息 */
    public String getMessage() {
        return mCurChapter.getMessage();
    }

    /** 设置获取章节内容返回的消息 */
    public void setMessage(String message) {
        this.mCurChapter.setMessage(message);
    }

    public String getFliePath() {
        return fliePath;
    }

    public void setFliePath(String fliePath) {
        this.fliePath = fliePath;
    }

    public int getTotalLength() {
        return totalLength;
    }

    public void setTotalLength(int totalLength) {
        this.totalLength = totalLength;
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public String getPercent1() {
        return mCurChapter.getPercent1();
    }

    public void setPercent1(String percent1) {
        this.mCurChapter.setPercent1(percent1);
    }

    public int getBookmarkByteOffset() {
        return mCurChapter.getBookmarkByteOffset();
    }

    public void setBookmarkByteOffset(int offset) {
        this.mCurChapter.setBookmarkByteOffset(offset);
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getChaptercontent() {
        return mCurChapter.getChapterContent();
    }

    public void setChaptercontent(String chaptercontent) {
        mCurChapter.setChaptercontent(chaptercontent);
    }

    public void setCurChapterCid(String cid) {
        mCurChapter.setChapterCid(cid);
    }

    public void setPreChapterCid(String cid) {
        mPrevChapter.setChapterCid(cid);
    }

    public void setNextChapterCid(String cid) {
        mNextChapter.setChapterCid(cid);
    }

    public String getCurChapterCid() {
        return mCurChapter.getChapterCid();
    }

    public String getPreChapterCid() {
        return mPrevChapter.getChapterCid();
    }

    public String getNextChapterCid() {
        return mNextChapter.getChapterCid();
    }

    public void setCurChapterPayMode(String payMode) {
        mCurChapter.setChapterPayMode(payMode);
    }

    public void setPreChapterPayMode(String payMode) {
        mPrevChapter.setChapterPayMode(payMode);
    }

    public void setNextChapterPayMode(String payMode) {
        mNextChapter.setChapterPayMode(payMode);
    }

    public String getCurChapterPayMode() {
        return mCurChapter.getChapterPayMode();
    }

    public String getPreChapterPayMode() {
        return mPrevChapter.getChapterPayMode();
    }

    public String getNextChapterPayMode() {
        return mNextChapter.getChapterPayMode();
    }

    public void setCurChapterPrice(String price) {
        mCurChapter.setChapterPrice(price);
    }

    public void setPreChapterPrice(String price) {
        mPrevChapter.setChapterPrice(price);
    }

    public void setNextChapterPrice(String price) {
        mNextChapter.setChapterPrice(price);
    }

    public String getCurChapterPrice() {
        return mCurChapter.getChapterPrice();
    }

    public String getPreChapterPrice() {
        return mPrevChapter.getChapterPrice();
    }

    public String getNextChapterPrice() {
        return mNextChapter.getChapterPrice();
    }

    public void setCurChapterWordCount(String wordCount) {
        mCurChapter.setChapterWordCount(wordCount);
    }

    public void setPreChapterWordCount(String wordCount) {
        mPrevChapter.setChapterWordCount(wordCount);
    }

    public void setNextChapterWordCount(String wordCount) {
        mNextChapter.setChapterWordCount(wordCount);
    }

    public String getCurChapterWordCount() {
        return mCurChapter.getChapterWordCount();
    }

    public String getPreChapterWordCount() {
        return mPrevChapter.getChapterWordCount();
    }

    public String getNextChapterWordCount() {
        return mNextChapter.getChapterWordCount();
    }

    /**
     * 获取当前章节名称
     * 
     * @return
     */
    public String getCurChapterName() {
        return mCurChapter.getChapterName();
    }

    public void setCurChapterName(String chapterName) {
        this.mCurChapter.setChapterName(chapterName);
    }

    /**
     * 获取上一章章节名称
     * 
     * @return
     */
    public String getPreChapterName() {
        return mPrevChapter.getChapterName();
    }

    public void setPreChapterName(String chapterName) {
        this.mPrevChapter.setChapterName(chapterName);
    }

    /**
     * 获取下一章章节名称
     * 
     * @return
     */
    public String getNextChapterName() {
        return mNextChapter.getChapterName();
    }

    public void setNextChapterName(String chapterName) {
        this.mNextChapter.setChapterName(chapterName);
    }

    /**
     * 返回 curChapterType 的值
     * 
     * @return curChapterType 1则成功获取信息,其他失败
     */

    public String getCurChapterType() {
        return mCurChapter.getChapterType();
    }

    public List<BookContentLineInfo> getCurChapterContentLines() {
        return mCurChapter.getContentLines();
    }

    public void curChapterLineIndexChanged(int delta) {
        mCurChapterLineIndex += delta;
        // Log4an.d("draw", "【curChapterLineIndexChanged】mCurChapterLineIndex=" +
        // mCurChapterLineIndex);
    }

    public void moveToPrevChapter() {
        mNextChapter = mCurChapter;
        mCurChapter = mPrevChapter;
        mPrevChapter = new BookChapterInfo(this);
    }

    public void moveToNextChapter() {
        mPrevChapter = mCurChapter;
        mCurChapter = mNextChapter;
        mNextChapter = new BookChapterInfo(this);
    }

    public void clearAll() {

    }

    public void doProcessSettingChanged(BookContentRender render, int divideByte) {
        // if (mPrevChapter != null) {
        // mPrevChapter.refreshContentLines(mCurChapterLineIndex, render);
        // }
        if (mCurChapter != null) {
            mCurChapter.refreshContentLines(mCurChapterLineIndex, divideByte, render);
        }
        // if (mNextChapter != null) {
        // mNextChapter.refreshContentLines(mCurChapterLineIndex, render);
        // }
    }

    public void refreshCurChapterContentLines(BookContentRender render, long divideByte) {
        if (mCurChapter != null) {
            mCurChapter.refreshContentLines(mCurChapterLineIndex, (int) divideByte, render);
        }
    }

    public void refreshPrevChapterContentLines(BookContentRender render, int divideByte) {
        if (mPrevChapter != null) {
            mPrevChapter.refreshContentLines(mCurChapterLineIndex, divideByte, render);
        }
    }

    public void refreshNextChapterContentLines(BookContentRender render) {
        if (mNextChapter != null) {
            mNextChapter.refreshContentLines(mCurChapterLineIndex, (int) markIndex, render);
        }
    }

    /** 判断是否阅读页可用 */
    public boolean isBookContentEnabled() {
        if (mCurChapter.getContentLines() == null
                || mCurChapterLineIndex + mCurSreenLineCount - 1 <= 0
                || mCurChapterLineIndex >= mCurChapter.getContentLines().size()) {
            return false;
        } else {
            return true;
        }
    }

    /***
     * 是否有下一页
     * 
     * @return
     */
    public boolean hasNotNextPage(BookContentParserBase bookContentParserBase) {
//        Log4an.i("draw", "【hasNotNextPage】当前lineIndex=" + getCurChapterLineIndex() + ",当前页行数="
//                + getCurSreenLineCount() + ",数据大小=" + getCurChapterContentLines().size()
//                + ",endIndex=" + getCurChapter().getEndIndex() + ",startIndex="
//                + getCurChapter().getStartIndex());
//         Log4an.e("draw", "【hasNotNextPage】type == " + (type == Constant.BOOKTYPE_ORDER_PAY)
//         + ",type--->" + type);
//         Log4an.i("draw", "【1】getCurChapterContentLines is null="
//         + (getCurChapterContentLines() == null ? true : getCurChapterContentLines().size()));
//         Log4an.i("draw", "【hasNotNextPage】" + "cid=" + getCurChapterCid() + ",isValid="
//         + getCurChapter().isValid() + ",preCid=" + getPreChapterCid() + ",nextCid="
//         + getNextChapterCid());
        return (type == Constant.BOOKTYPE_ORDER_PAY ? (!TextUtils.isEmpty(getNextChapterCid()) ? false
                : true)
                : getCurChapterContentLines() != null
                        && getCurChapterLineIndex() + getCurSreenLineCount() >= getCurChapterContentLines()
                                .size()
                        && !bookContentParserBase.hasNextChapter(getCurChapter().getEndIndex()));
    }

    public boolean hasNotPrevPage(BookContentParserBase bookContentParserBase) {
//        Log4an.i("draw", "【hasNotPrevPage】curLineIndex=" + getCurChapterLineIndex()
//                + ",startIndex=" + getCurChapter().getStartIndex());
        if (getCurChapterLineIndex() <= 1
                && !bookContentParserBase.hasPreChapter(getCurChapter().getStartIndex() - 1)) {
//            Log4an.i("draw", "【hasNotPrevPage】1111111111111111111111");
            return true;
        } else {
//            Log4an.i("draw", "【hasNotPrevPage】222222222222222222222");
            return false;
        }
    }

    public void turnPrevPage(BookContentParserBase bookContentParserBase,
            BookContentRender bookContentRender) {
        if (mCurChapterLineIndex - mCurSreenLineCount < 0) {
            turnPrevChapter(bookContentParserBase, bookContentRender);
            setCurChapterLineIndex(getCurChapterContentLines().size()
                    - getCurChapterContentLines().size() % mCurSreenLineCount);
        } else {
            curChapterLineIndexChanged(-mCurSreenLineCount);
        }
    }

    public void turnPrevChapter(BookContentParserBase bookContentParserBase,
            BookContentRender bookContentRender) {
        moveToPrevChapter();
        bookContentParserBase.getCurInfos(ShuqiApplication.getContext(), this, false);
        resetPayType();
        refreshCurChapterContentLines(bookContentRender, (int) markIndex);
        setCurChapterLineIndex(0);
    }

    public void turnNextPage(BookContentParserBase bookContentParserBase,
            BookContentRender bookContentRender) {
        if (mCurChapterLineIndex + mCurSreenLineCount > getCurChapterContentLines().size()) {
            turnNextChapter(bookContentParserBase, bookContentRender);
        } else {
            curChapterLineIndexChanged(mCurSreenLineCount);
        }
    }

    public void turnNextChapter(BookContentParserBase bookContentParserBase,
            BookContentRender bookContentRender) {
        moveToNextChapter();
        bookContentParserBase.getCurInfos(ShuqiApplication.getContext(), this, false);
        resetPayType();
        refreshCurChapterContentLines(bookContentRender, (int) markIndex);
        setCurChapterLineIndex(0);
    }

    public void turnToChapter(BookCataLog catalogInfo) {
        setCurChapterName(catalogInfo.getChapterName());
        setCurChapterCid(catalogInfo.getChapterId());
        setCurChapterPayMode(String.valueOf(catalogInfo.getPayMode()));
        setCurChapterPrice(catalogInfo.getChapterPrice());
//        if (catalogInfo.getDownloadState() == BookCataLog.HAS_DOWN) {
//            setNeedBuy(false);
//        } else {
            setNeedBuy(getDoNotAutoBuyState());
//        }
    }

    private boolean getDoNotAutoBuyState() {
        BookInfo bookInfo = BookInfoDao.getInstance().getBookInfo(null, getBookId(), getUid());
        if (bookInfo == null)
            return false;
        if (BookInfo.DEFAULT_NO_AUTO_BUY == bookInfo.getBookAutoBuyState()
                || BookInfo.NO_AUTO_BUY == bookInfo.getBookAutoBuyState()) {
            return true;
        } else if (BookInfo.AUTO_BUY == bookInfo.getBookAutoBuyState()) {
            return false;
        }
        return true;
    }

    private String TAG_SHOW_PERENT = "showPercent";

    /**
     * 获取已读的百分比 书包类型无法获取到
     * 
     * @return
     */
    public float getReadedProgress() {
        if ((getType() == Constant.BOOKTYPE_TXT) || getType() == Constant.BOOKTYPE_UMD) {
            if (mCurChapterLineIndex + mCurSreenLineCount < mCurChapter.getContentLines().size()) {
                // Log4an.i(
                // TAG_SHOW_PERENT,
                // "【getReadedProgress】行索引="
                // + mCurChapterLineIndex
                // + ",行数="
                // + mCurSreenLineCount
                // + ",当前屏幕结尾字节："
                // + mCurChapter.getContentLines()
                // .get(mCurChapterLineIndex + mCurSreenLineCount)
                // .getEndIndex() + ",文件大小：" + getTotalLength());
                int endIndex =
                        BookContentRender.PARAGRAPH_SPACE.equals(mCurChapter.getContentLines()
                                .get(mCurChapterLineIndex + mCurSreenLineCount).getContent()) ? mCurChapter
                                .getContentLines()
                                .get(mCurChapterLineIndex + mCurSreenLineCount - 1).getEndIndex()
                                : mCurChapter.getContentLines()
                                        .get(mCurChapterLineIndex + mCurSreenLineCount)
                                        .getEndIndex();

                return endIndex / (float) getTotalLength();
            }
            return mCurChapter.getEndIndex() / (float) getTotalLength();
        } else if (getType() == Constant.BOOKTYPE_EPUB) {
            return BookContentUtils.getChapterPercent(Integer.valueOf(getCurChapterCid()),
                    getTotalLength());
        } else {// 其他格式的百分比
            if (type == Constant.BOOKTYPE_PAY || type == Constant.BOOKTYPE_ORDER_PAY
                    || type == Constant.BOOKTYPE_NET) {
                BookCataLog catalogInfo =
                        BookCataLogDao.getInstance().getBookCatalogByCid(getUid(), getBookId(),
                                getSourceId(), getCurChapterCid());
                if (mBookInfo != null && mBookInfo.getBookMaxOid() > 0) {
                    return catalogInfo != null ? ((float) catalogInfo.getOId() / mBookInfo
                            .getBookMaxOid()) : 0;
                }
            } else {
                if (getCurChapterContentLines() != null && getCurChapterContentLines().size() > 0) {
                    return (mCurChapterLineIndex + mCurSreenLineCount)
                            / getCurChapterContentLines().size();
                }
            }
            return 0;
        }
    }

    /***
     * 获得本地文件的当前页的startIndex值
     * 
     * @return
     */
    private int getOffestIndex() {

        if (getCurChapterContentLines() != null
                && getCurChapterContentLines().size() > mCurChapterLineIndex) {
            final BookContentLineInfo lineInfo =
                    getCurChapterContentLines().get(mCurChapterLineIndex);
            // Log4an.e("yjd", "【getOffestIndex】lineInfo is null="
            // + (lineInfo == null ? true : lineInfo.getFirstIndex()));
            if (lineInfo != null) {
                // Log4an.e("yjd", "1.lineInfo.getContent()=" + lineInfo.getContent());
                if (BookContentRender.PARAGRAPH_SPACE.equals(lineInfo.getContent())) {
                    BookContentLineInfo lineInfo1 =
                            getCurChapterContentLines().get(mCurChapterLineIndex + 1);
                    if (lineInfo1 != null) {
                        // Log4an.e("yjd", "00.lineInfo1.getFirstIndex()=" +
                        // lineInfo1.getFirstIndex()
                        // + ",info=" + lineInfo1.getContent());
                        return lineInfo1.getFirstIndex();
                    }
                }
                // Log4an.e("yjd", "1.lineInfo.getFirstIndex()=" + lineInfo.getFirstIndex());
                return lineInfo.getFirstIndex();
            }
        }
        // Log4an.e("yjd", "2.lineInfo.getFirstIndex()=0");
        return 0;
    }

    // public void resetLocalStartIndex() {
    // setStartIndex(getOffestIndex());
    // }

    /***
     * 重置当前的文件偏移量
     */
    public void resetCurChapterOffestIndex() {
        this.mCurChapter.setBookmarkByteOffset(getOffestIndex());
    }

    public int getReadState() {
        int readState = BookContentModel.READ_STATE_NORMAL;
        switch (type) {
            case Constant.BOOKTYPE_NET:
                readState = BookContentModel.READ_STATE_NORMAL;
                break;
            case Constant.BOOKTYPE_ORDER_PAY:
                readState = BookContentModel.READ_STATE_PAY;
                break;
            case Constant.BOOKTYPE_PAY:
                readState =
                        isNeedBuy ? BookContentModel.READ_STATE_PAY
                                : BookContentModel.READ_STATE_NORMAL;
                break;
            default:
                break;
        }

        return readState;
    }

    public int getIntCurChapterCid() {
        try {
            return Integer.parseInt(getCurChapterCid());
        } catch (Exception e) {
            return 0;
        }
    }

    public void resetPayType() {
        if (type == Constant.BOOKTYPE_PAY || type == Constant.BOOKTYPE_ORDER_PAY) {
            if (BookContentUtils.TYPE_HAS_READ.equals(getCurChapterType())) {
                setType(Constant.BOOKTYPE_PAY);
            } else if (BookContentUtils.TYPE_NEDD_BUY.equals(getCurChapterType())) {
                setType(Constant.BOOKTYPE_ORDER_PAY);
            } else if (BookContentUtils.TYPE_NO_LOGIN.equals(getCurChapterType())) {
                setType(Constant.BOOKTYPE_ORDER_PAY);
            }
        }
    }
}
